/**
 * Created by zhaoyou on 30/08/2017.
 */
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());


var URLHelper = {};
URLHelper.prefixUrl = location.protocol + "//" + location.host + '/';

URLHelper.finddataurl=function(){
    return this.prefixUrl+'/findData';
}
URLHelper.dataurl=function(){
    return this.prefixUrl+ '/data';
}
URLHelper.loginurl=function(){
    return this.prefixUrl+ '/login';
}
URLHelper.loaddataurl=function(){
    return this.prefixUrl+ '/v/new';
}

URLHelper.historyDataUrl = function(tagId, startTime, endTime) {
    return URLHelper.prefixUrl + 'v/query?tagId=' + tagId + '&startTime=' + startTime + '&endTime=' + endTime;
};


URLHelper.ajax = function(url, method, data, callback, errorFun) {
    var self = this;
    //var localurl = window.location.pathname + window.location.search;
    if (typeof url === 'string') {
        $.ajax({
            'url' : url,
            'method' : method,
            'dataType' : 'json',
            'data': data,
            'success': function(data) {
                console.log(data);
                $('.errStyle').remove();
                callback(data);
            },
            'complete': function(req) {
                console.log(req.status);
                if(req.status == 401) {
                    window.location.href = "/toLogin";
                }
            },
            'error': errFun
        });
    } else if  (typeof  url === 'object') {
        if (!url['complete']) {
            url['complete'] = function(req) {if(req.status == 401) {  window.location.href = "/toLogin"; }}
        }
        url['error'] = errFun;
        var originFuc = url['success'];
        url['success'] = function(data) {
            $('.errStyle').remove();
            originFuc(data);
        }
        $.ajax(url);
    } else {
        alert('非法参数');
    }
};

function errFun(err) {
    var str = '';
    if(err.responseText != '') {
        str = '服务器发生了错误';
        console.log(err);
    } else {
        str = "网络连接异常";
    }
    var divs = $('.errStyle').html();
    if(divs) {
        $('.errStyle').html(str);
    } else {
        var htmlStr = "<div class='errStyle form-control text-center'>"+str+"</div>";
        $('body').append(htmlStr);
    }
};
